// pages/mine/modifyInfor/modifyInfor.js
import WeCropper from '../../../we-cropper/we-cropper.js';

const device = wx.getSystemInfoSync();
const width = device.windowWidth;
const height = device.windowHeight;
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //基本信息
    nickName_text: '',
    nickName_num: '',
    signature_text: '',
    signature_num: '',

    register_info: [],


    //弹框
    flag_sex: false,
    flag_nickName: false,
    flag_signature: false,
    tailor_show: true,

    is_trueName:false,
    //裁剪后的图片
    img_url: '',
    img_base64: '',

    // 裁剪图片
    cropperOpt: {
      id: 'cropper',
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 300) / 2,
        y: (height - 300) / 2,
        width: 300,
        height: 300
      }
    },
  },
  //select_cancel
  select_cancel(){
    this.setData({
      flag_sex: false,
    })
  },
  //select_man
  select_man(){
    this.confirm_info("sex", "M");
    wx.setStorageSync("reg_sex", "M")
    this.setData({
      flag_sex: false,
    })
  },
  select_woman(){
    this.confirm_info("sex", "F");
    wx.setStorageSync("reg_sex", "F")
    this.setData({
      flag_sex: false,
    })
  },
  //更新个人信息请求
  confirm_info(_field, _value){
    let that = this;
    wx.request({
      url: app.globalData.url + 'api/mine/update/info',
      data: {
        token:app.globalData.token,
        field: _field,
        value: _value,
      },
      method: 'POST',
      success: function(e) {
        // console.log(e)
        that.get_register_info();
      },
    })
  },
  sure_signature(){
    this.confirm_info("signature", this.data.signature_text);
    wx.setStorageSync("reg_signature", this.data.signature_text);
    this.setData({
      flag_signature: false,
    })
  },
  sure_nickName() {
    this.is_nickName(this.data.nickName_text);
    if (this.data.is_trueName){
      this.confirm_info("nickname", this.data.nickName_text);
      wx.setStorageSync("reg_nickname", this.data.nickName_text);      
    }else{
      wx.showToast({
        title: '已存在重复昵称',
        icon:'none',
      })
    }
    this.setData({
      flag_nickName: false,
    })
  },
  //更改签名
  click_signature() {
    let that = this;
    this.setData({
      flag_signature: true,
    })
  },
  //更改性别
  click_sex() {
    let that = this;
    this.setData({
      flag_sex: true,
    })
  },
  //更改昵称
  click_nickName() {
    let that = this;
    this.setData({
      flag_nickName: true,
    })
  },
  //更改头像
  click_avatarImg() {
    let that = this;
    this.setData({
      tailor_show: false,
    })
  },
  //输入签名
  inp_signature(e) {
    let that = this;
    // console.log(e.detail.value)
    let signature_text = e.detail.value,
      signature_num = e.detail.cursor;
    that.setData({
      signature_text: signature_text,
      signature_num: signature_num,
    })
  },
  //输入昵称
  inp_nickName(e) {
    let that = this;
    // console.log(e.detail.value)
    let nickName_text = e.detail.value,
      nickName_num = e.detail.cursor;
    that.is_nickName(nickName_text);
    that.setData({
      nickName_text: nickName_text,
      nickName_num: nickName_num,
    })
  },
  //判断昵称是否重复
  is_nickName(_nickname) {
    let that = this;
    wx.request({
      url: app.globalData.url + 'api/common/repeat/nickname',
      data: {
        token: app.globalData.token,
        nickname: _nickname,
      },
      method: 'POST',
      success: function(e) {
        // console.log(e)
        if (e.data.message =="该昵称可以使用"){
          that.setData({
            is_trueName: "true",
          })
        }
      },
    })
  },
  //获取用户信息
  get_register_info() {
    let that = this;
    wx.request({
      url: app.globalData.url + 'api/common/register/info',
      data: {
        token: app.globalData.token,
      },
      method: 'POST',
      success: function(e) {
        // console.log(e.data.data.register_info)
        let register_info = e.data.data.register_info;
        that.setData({
          register_info: register_info,
        })
      },

    })
  },
  //选择 裁剪图片
  click_close: function() {
    this.setData({
      tailor_show: true,
    })
  },
  touchStart(e) {
    this.wecropper.touchStart(e)
  },
  touchMove(e) {
    this.wecropper.touchMove(e)
  },
  touchEnd(e) {
    this.wecropper.touchEnd(e)
  },
  getCropperImage() {
    wx.showLoading({
      title: '加载中~',
      icon: "none",
    })
    let that = this;
    this.wecropper.getCropperImage((src) => {
      if (src) {
        // console.log('图片+'+src)
        var image_base64 = wx.getFileSystemManager().readFileSync(src, "base64")
        //发送请求
        wx.request({
          url: app.globalData.url + 'api/mine/upload/avatar',
          method: "POST",
          header: {
            "content-type": "application/x-www-form-urlencoded"
          },
          data: {
            token: app.globalData.token,
            image: image_base64 + '',
          },
          success: function(e) {
            // console.log(e.data.data.file_url)
            let file_url = e.data.data.file_url;
            wx.setStorageSync("reg_avatar_url", file_url)
          }
        })
        that.setData({
          img_url: src,
          img_base64: image_base64 + '',
          tailor_show: true,
        })
        let timer = setTimeout(function() {
          that.get_register_info();
          clearTimeout(timer);
        }, 1000)

        wx.hideLoading();

      } else {
        console.log('获取图片地址失败，请稍后重试')
      }

    });
  },
  uploadTap() {
    const self = this;

    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        const src = res.tempFilePaths[0]
        //  获取裁剪图片资源后，给data添加src属性及其值
        self.wecropper.pushOrign(src)
      }
    })
  },
  //裁剪图片 初始化
  init: function() {
    const {
      cropperOpt
    } = this.data

    new WeCropper(cropperOpt)
      .on('ready', (ctx) => {
        console.log(`wecropper is ready for work!`)
      })
      .on('beforeImageLoad', (ctx) => {
        console.log(`before picture loaded, i can do something`)
        console.log(`current canvas context:`, ctx)
        wx.showToast({
          title: '上传中',
          icon: 'loading',
          duration: 20000
        })
      })
      .on('imageLoad', (ctx) => {
        console.log(`picture loaded`)
        console.log(`current canvas context:`, ctx)
        wx.hideToast()
      })
      .on('beforeDraw', (ctx, instance) => {
        console.log(`before canvas draw,i can do something`)
        console.log(`current canvas context:`, ctx)
      })
      .updateCanvas()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    this.init();
    this.get_register_info();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.get_register_info();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})